<script setup lang="tsx">
import {
  ElButton,
  ElInput,
  ElSpace,
  ElMessage,
  ElPopconfirm,
  ElMessageBox,
  ElTag,
  // ElSelect,
  ElSelectV2,
  // ElOption,
} from "element-plus";
import { MyIcon } from "@/components/MyIcon";
import { onMounted, ref } from "vue";
import UserForm from "./component/UserForm.vue";
import { userApi } from "@/api/admin/user";
import { deepClone } from "@/utils";
// import UserRoleForm from "./component/UserRoleForm.vue";
import { roleApi } from "@/api/admin/role";
import { permissionApi } from "@/api/admin/permission";
import { LyTable } from "@/components/Table";
import { BASE_URL } from "@/api";

const UserFormRef = ref<any>(null);
// const UserRoleFormRef = ref<any>(null);
const params = ref({
  account: "",
  roleId: "",
});

const lyTableRef = ref<any>(null);

const userTable = ref<any>([]);

// const roleData = ref<any>([]);

const roleOptions = ref<any>([]);

const permissionMetaData = ref<any>([]);

const columns = ref<any>([
  {
    prop: "selection",
    align: "center",
    type: "selection",
  },
  {
    prop: "index",
    label: "序号",
    align: "center",
    hidden: false,
    // width:"50px",
    render: (row: any, index: number) => {
      row
      return index + 1;
    }
  },
  {
    prop: "avatar",
    align: "center",
    label: "头像",
    render: (row: any) => {
      const src = BASE_URL + '/files' + '/' + row.avatar
      if(row.avatar){
        return <img src={src} style={{ width: '100%', height: '1005' }} />
      }else{
        return <span></span>
      }
    }
  },
  {
    prop: "account",
    align: "center",
    label: "用户名",
  },
  {
    prop: "roles",
    align: "center",
    label: "角色",
    // width: "100px",
    showOverflowTooltip: true,
    render: (row: any) => {
      return <>
        {
          row.roles.map((item: any) => {
            return <span><ElTag type="info">{item.name}</ElTag>&nbsp;</span>
          })
        }
      </>
    }
  },
  {
    prop: "createTime",
    align: "center",
    label: "创建时间",
  },
  {
    prop: "updateTime",
    align: "center",
    label: "最近更新",
  },
  {
    prop: "",
    label: "操作",
    align: "center",
    render: (row: any) => {
      return (
        <>
          <ElSpace>
            <ElButton v-per="user_update" onClick={() => { handleEdit(row) }} link type="primary" size="small">
              <MyIcon color="#409EFF" icon="el:EditPen" />
            </ElButton>
            {/* <ElButton onClick={() => { handleAddUserRole(row) }} link type="primary" size="small">
              <MyIcon color="#409EFF" icon="el:Operation" />
            </ElButton> */}
            <ElPopconfirm title="确定要删除吗？" confirm-button-text="删除" cancel-button-text="取消" confirm-button-type="danger"
              cancel-button-type="info" onConfirm={() => { handleDel(row.id) }} hideAfter={0}>
              {{
                reference: () => {
                  return <ElButton v-per="user_remove" type="danger" link size="small">
                    <MyIcon color="#F56C6C" icon="el:Delete" />
                  </ElButton>
                }
              }}
            </ElPopconfirm>
          </ElSpace >
        </>
      )
    },
  },
])

// 分页
const page = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [5, 10, 15, 20],
  layout: "total, sizes, prev, pager, next, jumper"
});

// 获取用户
const getUser = async () => {
  const newPage = { ...page.value, layout: null, pageSizes: null, total: null };
  const ret = await userApi.getUserApi({ ...params.value, ...newPage });
  if (ret.code === 200) {
    userTable.value = ret.data.data;
    page.value.total = ret.data.total;
  } else {
    ElMessage.error(ret.data.msg);
  }
};

// 获取角色数据
const getRole = async () => {
  const ret = await roleApi.getRoleApi({});
  if (ret.code === 200) {
    roleOptions.value = ret.data.map((item: any) => ({ label: item.name, value: item.id }));
    // console.log(roleOptions.value);    
  }
};

// 递归将权限树设置为平面
const permissionTreeToList = (permissionTree: any) => {
  const permissionList: any = [];
  permissionTree.forEach((item: any) => {
    if (item.children && item.children.length) {
      permissionList.push({ ...item, children: undefined });
      const permissionChildren = permissionTreeToList(item.children);
      permissionList.push(...permissionChildren);
    } else {
      permissionList.push(item);
    }
  });
  return permissionList;
};

// 获取权限元数据
const getPermissionMetaTree = async () => {
  const ret = await permissionApi.permissionMetaTree();
  if (ret.code === 200) {
    // console.log(ret.data);

    // console.log(permissionTreeToList(ret.data));
    permissionMetaData.value = permissionTreeToList(ret.data);
  } else {
    ElMessage.error("获取权限失败");
    throw new Error("获取权限失败");
  }
};

onMounted(() => {
  getPermissionMetaTree();
  getUser();
  getRole();
});

// 刷新
const onRefresh = () => {
  getPermissionMetaTree();
  getUser();
  getRole();
};


// 防抖查询
// const debounceQuery = debounce(() => {
//   getUser();
// }, 500);

// // 监听params.title
// watch(
//   () => params.value.account,
//   () => {
//     debounceQuery();
//   }
// );

// 分页改变
const currentChange = (value: number) => {
  page.value.currentPage = value;
  getUser();
};

// 添加用户角色
// const handleAddUserRole = (user: any) => {
//   const newUser = deepClone(user);
//   UserRoleFormRef.value.open(newUser);
// };
const handleAdd = () => {
  UserFormRef.value.open();
  // console.log("添加");
};
const handleEdit = (user: any) => {
  const newUser = deepClone(user);
  newUser.roles = newUser.roles.map((item: any) => item.id);
  UserFormRef.value.open(newUser);
};

const handleDel = async (id: string) => {
  const ret = await userApi.removeUser(id);
  if (ret.code === 200) {
    getUser();
    ElMessage.success("删除成功");
  } else {
    ElMessage.error(ret.data.msg);
  }
};

// 批量删除
const batchRemove = async () => {
  const SelectionRows = lyTableRef.value.tableRef.getSelectionRows()

  if (SelectionRows.length == 0) {
    ElMessage({
      type: 'info',
      message: '未勾选要删除的数据！',
    })
    return
  }

  ElMessageBox.confirm(
    '确定要删除所选数据吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const ids = SelectionRows.map((item: any) => item.id)
    const res = await userApi.batchRemoveUser(ids)
    if (res.code == 200) {
      getUser();
      ElMessage({
        type: 'success',
        message: '删除成功!',
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '删除取消',
    })
  })
}

// 批量修改
const batchUpdate = () => {
  const SelectionRows = lyTableRef.value.tableRef.getSelectionRows()
  if (SelectionRows.length == 0) {
    ElMessage({
      type: 'info',
      message: '请选择要修改的数据',
    })
    return
  }
  const newUser = deepClone(SelectionRows);
  UserFormRef.value.open(newUser, true);
}

const openColumnSetting = () => {
  lyTableRef.value.openColumnSetting();
}

const updateColumnSetting = (columnsData: any) => {
  columns.value = columnsData;
}

const tableOption = ref({
  columns,
  data: userTable,
  page: page,
  // currentChange,
})
</script>

<template>
  <div>
    <UserForm :roleOptions="roleOptions" ref="UserFormRef" @update="getUser" />
    <!-- <UserRoleForm ref="UserRoleFormRef" :permissionMetaData="permissionMetaData" @update="getUser" :roleData="roleData" /> -->
    <LyTable :isShowPage="true" ref="lyTableRef" v-bind="tableOption" pageVerticalAlign="top"
      @currentChange="currentChange" @updateColumnSetting="updateColumnSetting">
      <template #tableTop>
        <div class="user-top">
          <div class="user-top-left">
            <el-button @click="onRefresh" type="" icon="Refresh" />
            <el-button v-per="'user_save'" @click="handleAdd" type="primary">添加</el-button>
            <el-button v-per="'user_update'" @click="batchUpdate" type="primary">批量修改</el-button>
            <el-button v-per="'user_removeBatch'" type="danger" @click="batchRemove">批量删除</el-button>
            <el-button type="primary" plain @click="openColumnSetting" icon="Tools"></el-button>
          </div>
          <div class="user-top-right">
            <ElSpace>
              <el-input clearable v-model="params.account" placeholder="请输入用户名" />
              <!-- <el-select style="width: 150px" clearable v-model="params.roleId" placeholder="请选择">
              <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select> -->
              <el-select-v2 v-model="params.roleId" style="min-width: 150px" :options="roleOptions as any"
                placeholder="请选择角色" multiple />
              <el-button @click="getUser" type="primary">搜索</el-button>
            </ElSpace>
          </div>
        </div>
      </template>
    </LyTable>
  </div>
</template>
<style scoped lang="less">
.page {
  margin-top: 10px;
  display: flex;
  justify-content: right;
}

.user-top {
  display: flex;
  justify-content: space-between;
}
</style>
